
$(document).ready(
    function() {
        var VAL = {
            NORMAL : "0000000",
            T_FBPLSTDAT : "FBPBISDAT",
            T_FIPINQBOX : "FIPINQBOX",
            T_FIPINQSHT : "FIPINQSHT",
            T_FSPBOXHLD : "FSPBOXHLD",
            // EVT_USER :$("#userId").text(),
            EVT_USER : "C1107020",
            DISABLED_ATTR : {
                'disabled' : true
            },
            ENABLED_ATTR : {
                'disabled' : false
            }
        };
        var domObj = {
            $boxIdFk : $("#boxIdFk"),
            $prdIdFk :$("#prdIdFk"),
            $boxId : $("#boxId"),
            $boxStat : $("#boxStat"),
            $prdQty : $("#prdQty"),
            $chipQty : $("#chipQty"),
            $nxPathIdFk : $("#nxPathIdFk"),
            $nxPathVerFk : $("#nxPathVerFk"),
            $nxOpeNoFk : $("#nxOpeNoFk"),
            $nxOpeIdFk : $("#nxOpeIdFk"),
            $nxOpeVerFk : $("#nxOpeVerFk"),
            $acRecipeId : $("#acRecipeId"),
            $toolIdFk : $("#toolIdFk"),
            $nxProcIdFk : $("#nxProcIdFk"),

            buttons : {
                $query_btn : $("#query_btn"),
                $selectReason_btn : $("#selectReason_btn"),
                $hold_btn   : $("#hold_btn"),
                $release_btn   : $("#release_btn"),
                $upload_btn : $("#upload_btn"),
                $select_file : $("#select_file"),
                $download_btn : $("#download_btn")
            },
            grids : {
                $reasonListGrd : $("#ReasonListGrd"),
                $reasonListDiv : $("#reasonListDiv"),
                $reasonListPg : $("#reasonListPg"),

                $glassListGrd : $("#glassListGrd"),
                $glassListDiv : $("#glassListDiv"),
                $glassListPg : $("#glassListPg"),

                $cstHoldListGrd : $("#cstHoldListGrd"),
                $cstHoldListDiv : $("#cstHoldListDiv"),
                $cstHoldListPg : $("#cstHoldListPg"),

            },
            dialogs : {
                $addReasonDialog : $("#addReasonDialog"),
                $deptId : $("#deptId"),
                $modalReasonListDiv : $("#modalReasonListDiv"),
                $modalReasonListGrd : $("#modalReasonListGrd"),
                $modalReasonListPg : $("#modalReasonListPg"),

                $ReasonListDiv : $("#ReasonListDiv"),
                $ReasonListGrd : $("#ReasonListGrd"),
                $ReasonListPg : $("#ReasonListPg"),

                // 对话框的确认按钮
                $reasonDialog_sureBtn : $("#reasonDialog_sureBtn")

            }

        }
        var lastrow, lastcell,lastId;
        var btnFunc = {
            //初始化保留信息
            iniCstHold : function () {
                $("#cstHoldListGrd").jqGrid('clearGridData');
                var boxIdFk = domObj.$boxIdFk.val();// 卡匣id
                inObjs = {
                    trx_id : VAL.T_FSPBOXHLD,
                    action_flg : "Q",
                    box_id : boxIdFk
                };
                outObjs = comTrxSubSendPostJson(inObjs);
                if (outObjs.rtn_code === VAL.NORMAL) {
                    if (outObjs.tbl_cnt > 0) {
                        setGridInfo(outObjs.oary, "#cstHoldListGrd");
                    }
                }
            },
            //卡匣查询
            queryBtnfunc : function() {
                clearDataAction();
                var boxIdFk,iarys,inObjs,outObjs;
                boxIdFk = domObj.$boxIdFk.val();// 卡匣id
                if ("" == boxIdFk) {
                    showErrorDialog("", "卡匣代码不能为空");
                    return false;
                }

                inObjs = {
                    trx_id : VAL.T_FIPINQBOX,
                    action_flg : "Q",
                    box_id : boxIdFk
                };
                outObjs = comTrxSubSendPostJson(inObjs);
                if (outObjs.rtn_code === VAL.NORMAL) {
                        domObj.$boxId.val(outObjs.box_id);
                        domObj.$boxStat.val(outObjs.box_stat);
                        domObj.$prdQty.val(outObjs.prd_qty);
                        domObj.$chipQty.val(outObjs.chip_qty);
                        domObj.$nxPathIdFk.val(outObjs.nx_path_id_fk);
                        domObj.$nxPathVerFk.val(outObjs.nx_path_ver_fk);
                        domObj.$nxOpeNoFk.val(outObjs.nx_ope_no_fk);
                        domObj.$nxOpeIdFk.val(outObjs.nx_ope_id_fk);
                        domObj.$nxOpeVerFk.val(outObjs.nx_ope_ver_fk);
                        if (outObjs.hasOwnProperty("oary")){
                            domObj.$acRecipeId.val(outObjs.oary[0].ac_recipe_id);
                        };
                        domObj.$toolIdFk.val(outObjs.tool_id_fk);
                        domObj.$nxProcIdFk.val(outObjs.nx_proc_id_fk);
                // 初始化玻璃信息
                    setGridInfo(outObjs.oary, "#glassListGrd");
                    btnFunc.iniCstHold();
                }
            },
            selectReasonBtnfunc : function() {
                domObj.dialogs.$modalReasonListGrd
                    .jqGrid("clearGridData");
                // 原因代码对话框的模型
                domObj.dialogs.$addReasonDialog.modal({
                    backdrop : true,
                    keyboard : false,
                    show : false
                });
                domObj.dialogs.$addReasonDialog.modal("show");

                comAddValueByDataCateFnc("#deptId","DEPT","data_ext","data_ext",true);
                // 加载原因代码
                    var deptId, iary, inObj, outObj;
                    deptId = domObj.dialogs.$deptId.val();
                    iary = {
                        data_cate : "HDRS",
                    };
                    inObj = {
                        trx_id : VAL.T_FBPLSTDAT,
                        action_flg : "Q",
                        iary : [ iary ]
                    };
                    outObj = comTrxSubSendPostJson(inObj);
                    if (outObj.rtn_code === VAL.NORMAL) {
                        var deptIds = domObj.dialogs.$deptId.val();
                        var oary = [];
                        for (var i = 0; i < outObj.oary.length; i++) {
                            var reason = {};
                            reason.dept_id = deptIds;
                            reason.data_ext = outObj.oary[i].data_ext;
                            reason.data_desc = outObj.oary[i].data_desc;
                            oary.push(reason);
                        }
                        setGridInfo(oary,"#modalReasonListGrd");
                    }
            },
            //保留
            // holdBtnfun_ : function () {
            //     var rowIds = domObj.dialogs.$ReasonListGrd.jqGrid('getDataIDs');
            //     rowData = domObj.dialogs.$ReasonListGrd.jqGrid(
            //         "getRowData", rowIds[0]);
            //     if(!rowData){
            //         showErrorDialog("", "当前原因代码信息为空！");
            //         return false;
            //     }
            //     var rsn_dept = rowData.dept_id;
            //     var rsn_cate = rowData.data_desc;
            //     var rsn_code = rowData.data_ext;
            //     var box_stat = $("#boxStat").val();
            //     var inObj,
            //         outObj,
            //     inObj = {
            //         rsn_dept : rsn_dept,
            //         rsn_cate : "HOLD",
            //         rsn_code : rsn_code,
            //         box_id   : domObj.$boxId.val(),
            //         box_stat : box_stat,
            //         evt_user : VAL.EVT_USER,
            //         trx_id: VAL.T_FSPBOXHLD,
            //         action_flg: 'H',
            //
            //     };
            //
            //     outObj = comTrxSubSendPostJson(inObj);
            //     if (outObj.rtn_code == VAL.NORMAL) {
            //         btnFunc.queryBtnfunc();
            //         btnFunc.iniCstHold();
            //         showSuccessDialog("保留成功");
            //     }
            // },
            holdBtnfun : function (){
                var rows = domObj.grids.$glassListGrd.jqGrid('getRowData');
                var rowIds = domObj.dialogs.$ReasonListGrd.jqGrid('getDataIDs');
                var rowData = domObj.dialogs.$ReasonListGrd.jqGrid(
                    "getRowData", rowIds[0]);
                if(rowIds.length == 0){
                    showErrorDialog("", "当前原因代码信息为空！");
                    return false;
                }
                if(rows.length <= 0){
                    showErrorDialog("","请将需要保留的玻璃放入玻璃列表中！")
                    return false;
                }
                var rsn_dept = rowData.dept_id;
                var rsn_cate = rowData.data_desc;
                var rsn_code = rowData.data_ext;
                var iary = [];
                for(var i = 0 ; i < rows.length ; i++){
                    var iaryA = {
                        prd_seq_id :rows[i].prd_seq_id
                    }
                    iary.push(iaryA);
                }
                var inObj = {
                    trx_id: VAL.T_FSPBOXHLD,
                    action_flg: 'H',
                    iary     : iary,
                    rsn_dept : rsn_dept,
                    rsn_cate : "HOLD",
                    rsn_code : rsn_code,
                    box_id   : domObj.$boxId.val(),
                    evt_user : VAL.EVT_USER
                };
                var outObj = comTrxSubSendPostJson(inObj);
                if(outObj.rtn_code === VAL.NORMAL){
                    if(crr_query == "Y"){
                        btnFunc.queryBtnfunc();
                        btnFunc.iniCstHold();
                    }
                    showSuccessDialog("保留成功");
                }
            },
            //释放
            moveBtnfun : function () {
                var rowId= domObj.grids.$cstHoldListGrd
                    .jqGrid("getGridParam", "selrow");
                rowData = domObj.grids.$cstHoldListGrd.jqGrid(
                    "getRowData", rowId);
                if(!rowData.hasOwnProperty("rsn_code")){
                    showErrorDialog("", "请选择一条Hold信息");
                    return false;
                }
                var evt_seq_id_fk = rowData['evt_seq_id_fk'];
                var rsn_dept = rowData.rsn_dept;
                var rsn_cate = rowData.rsn_cate;
                var rsn_code = rowData.rsn_code;
                var box_stat = $("#boxStat").val();
                var inObj,
                    outObj,
                    inObj = {
                        box_id   : domObj.$boxId.val(),
                        box_stat : box_stat,
                        rsn_dept : rsn_dept,
                        rsn_cate : rsn_cate,
                        rsn_code : rsn_code,
                        evt_seq_id_fk : evt_seq_id_fk,
                        evt_user : VAL.EVT_USER,
                        trx_id: VAL.T_FSPBOXHLD,
                        action_flg: 'M',

                    };

                outObj = comTrxSubSendPostJson(inObj);
                if (outObj.rtn_code == VAL.NORMAL) {
                    btnFunc.queryBtnfunc();
                    btnFunc.iniCstHold();
                    showSuccessDialog("释放成功");
                }
            },
            downloadTempFun: function () {
                if ($("#downForm").length > 0) {
                    $("#downForm").remove();
                }
                var str = '<form id="downForm" action="download.do" method="post">';
                str = str + '<input type="hidden" name="fileName" id= "fileName" />';
                str = str + "</form>";

                $(str).appendTo("body");
                $("#fileName").val("2400.xls");
                $("#downForm").submit();
            }

        }
        // 主页面grid初始化
        var iniGridInfo = function() {

            domObj.grids.$glassListGrd.jqGrid({
                url : "",
                datatype : "local",
                mtype : "POST",
                height : 470,
                width : 425,
                autowidth : false,
                shrinkToFit : false,
                resizable : true,
                loadonce : true,
                viewrecords : true,
                rownumbers : true,
                rowNum : 20,
                emptyrecords : true,
                multiselect : false,
                pager : domObj.grids.$glassListPg,
                colModel : [ {
                    name : 'slot_no',
                    index : 'slot_no',
                    label : '子格位',
                    width : 90
                }, {
                    name : 'prd_seq_id',
                    index : 'prd_seq_id',
                    label : '玻璃代码',
                    width : 150
                }, {
                    name : 'prd_qty',
                    index : 'prd_qty',
                    label : '面板计数',
                    width : 120
                }, {
                    name : 'prd_grade',
                    index : 'prd_grade',
                    label : '面板等级',
                    width : 120
                }
                ]
            });
        }
        domObj.dialogs.$ReasonListGrd
            .jqGrid({
                url : "",
                datatype : "local",
                mtype : "POST",
                height : 150,
                // width :
                // domObj.dialogs.$modalReasonListDiv.width()*0.99,
                width :  455,
                autowidth : false,
                shrinkToFit : true,
                resizable : true,
                loadonce : true,
                viewrecords : true,
                rownumbers : true,
                rowNum : 20,
                emptyrecords : true,
                multiselect : false,
                pager : domObj.dialogs.$ReasonListPg,
                colModel : [ {
                    name : 'dept_id',
                    index : 'dept_id',
                    label : '部门代码',
                    width : 100
                }, {
                    name : 'data_ext',
                    index : 'data_ext',
                    label : '原因代码',
                    width : 150
                }, {
                    name : 'data_desc',
                    index : 'data_desc',
                    label : '原因代码说明',
                    width : 180
                } ]
            });
        domObj.grids.$cstHoldListGrd
            .jqGrid({
                url : "",
                datatype : "local",
                mtype : "POST",
                height : 220,
                // width :
                // domObj.dialogs.$modalReasonListDiv.width()*0.99,
                width :  480,
                autowidth : false,
                shrinkToFit : false,
                resizable : true,
                loadonce : true,
                viewrecords : true,
                rownumbers : true,
                rowNum : 20,
                emptyrecords : true,
                multiselect : false,
                pager : domObj.grids.$cstHoldListPg,
                colModel : [
                    {
                        name : 'rsn_dept',
                        index : 'rsn_dept',
                        label : '部门代码',
                        width : 60
                    }, {
                        name : 'rsn_code',
                        index : 'rsn_code',
                        label : '原因代码',
                        width : 60
                    }, {
                        name : 'rsn_cate',
                        index : 'rsn_cate',
                        label : '原因类型',
                        width : 50
                    },
                    {
                    name : 'evt_seq_id_fk',
                    index : 'evt_seq_id_fk',
                    label : '唯一码',
                    width : 70,
                    key:true
                }, {
                    name : 'evt_usr',
                    index : 'evt_usr',
                    label : '操作人',
                    width : 70
                }, {
                    name : 'evt_timestamp',
                    index : 'evt_timestamp',
                    label : '操作时间',
                    width : 150
                } ]
            });


        var inModelGrid = function() {
            domObj.dialogs.$modalReasonListGrd
                .jqGrid("clearGridData");
            domObj.dialogs.$modalReasonListGrd
                .jqGrid({
                    url : "",
                    datatype : "local",
                    mtype : "POST",
                    height : 300,
                    // width :
                    // domObj.dialogs.$modalReasonListDiv.width()*0.99,
                    width : 355,
                    autowidth : false,
                    shrinkToFit : false,
                    resizable : true,
                    loadonce : true,
                    viewrecords : true,
                    rownumbers : true,
                    rowNum : 20,
                    emptyrecords : true,
                    multiselect : false,
                    pager : domObj.dialogs.$modalReasonListPg,
                    colModel : [ {
                        name : 'dept_id',
                        index : 'dept_id',
                        label : '部门代码',
                        hidden : true,
                        width : 100
                    }, {
                        name : 'data_ext',
                        index : 'data_ext',
                        label : '原因代码',
                        width : 150
                    }, {
                        name : 'data_desc',
                        index : 'data_desc',
                        label : '原因代码说明',
                        width : 180
                    } ],

                });


        };
        var dialogFnc = {
            reasonSureFnc : function() {
                var deptId = domObj.dialogs.$deptId.val();
                if(!deptId){
                    showErrorDialog("", "请选择部门代码");
                    return false;
                }
                var rowId= domObj.dialogs.$modalReasonListGrd
                    .jqGrid("getGridParam", "selrow");
                var rowData = domObj.dialogs.$modalReasonListGrd.jqGrid(
                    "getRowData", rowId);
                if(!rowData.hasOwnProperty("data_ext")){
                    showErrorDialog("", "请选择一条原因代码");
                    return false;
                }
                rowData.dept_id = deptId;
                setGridInfo(rowData, "#ReasonListGrd");
                domObj.dialogs.$addReasonDialog.modal("hide");
          }
        }
        var iniButtonAction = function() {
            domObj.buttons.$query_btn.click(function() {
                btnFunc.queryBtnfunc();
            });
            domObj.buttons.$selectReason_btn.click(function() {
                btnFunc.selectReasonBtnfunc();

            });
            domObj.buttons.$hold_btn.click(function () {
                btnFunc.holdBtnfun();
            });
            domObj.buttons.$release_btn.click(function () {
                btnFunc.moveBtnfun();
            });
            domObj.buttons.$download_btn.click(function () {
                btnFunc.downloadTempFun();
            });

            // 确认按钮绑定click事件函数
            domObj.dialogs.$reasonDialog_sureBtn.bind('click',
                dialogFnc.reasonSureFnc);
            domObj.buttons.$select_file.bind('click',
                select_file);
            domObj.buttons.$upload_btn.change(function() {
                uploadFnc(this);
            });

        }
        var clearDataAction = function() {
            domObj.$boxId.val("");
            domObj.$boxStat.val("");
            domObj.$prdQty.val("");
            domObj.$chipQty.val("");
            domObj.$nxPathIdFk.val("");
            domObj.$nxPathVerFk.val("");
            domObj.$nxOpeNoFk.val("");
            domObj.$nxOpeIdFk.val("");
            domObj.$nxOpeVerFk.val("");
            domObj.$acRecipeId.val("");
            domObj.$toolIdFk.val("");
            domObj.$nxProcIdFk.val("");
            $("#ReasonListGrd").jqGrid('clearGridData');
            $("#glassListGrd").jqGrid('clearGridData');
            $("#modalReasonListGrd").jqGrid('clearGridData');
            $("#cstHoldListGrd").jqGrid('clearGridData');
        }
        var otherActionBind = function(){
            //Stop from auto commit
            $("form").submit(function(){
                return false;
            });

        };
        function select_file() {
            document.getElementById("upload_btn").click();
        }
        function uploadFnc(obj) {
            crr_query="N";
            /*
             FileReader共有4种读取方法：
             1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
             2.readAsBinaryString(file)：将文件读取为二进制字符串
             3.readAsDataURL(file)：将文件读取为Data URL
             4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
             */
            var wb;//读取完成的数据
            var rABS = false; //是否将文件读取为二进制字符串
            if(!obj.files) {
                return;
            }
            var fileName = obj.value;
            if(fileName.length > 1 && fileName ) {
                var ldot = fileName.lastIndexOf(".");
                var type = fileName.substring(ldot + 1);
                if(!(type=="xlsx"||type=="xls")) {
                    showErrorDialog("", "只能上传excel文件");
                    return;
                }
                // var length = fileName.lastIndexOf("\\");
                // var name = fileName.substring(length + 1);
                // if(name!=null) {
                //     domObj.buttons.$file_name.val(name);
                // }

            }
            var f = obj.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var data = e.target.result;
                if(rABS) {
                    wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                        type: 'base64'
                    });
                } else {
                    wb = XLSX.read(data, {
                        type: 'binary'
                    });
                }
                //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                //wb.Sheets[Sheet名]获取第一个Sheet的数据
                var data = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                var Data= [];
                var inObj,outObj;
                for(var i=0;i<data.length;i++){
                    inObj = {
                        trx_id : VAL.T_FIPINQSHT,
                        action_flg : "Q",
                        prd_seq_id : data[i].prd_seq_id
                    };
                    outObj = comTrxSubSendPostJson(inObj);
                    if (outObj.rtn_code === VAL.NORMAL) {
                        // Data[i]=outObj;
                        var dataObj = {
                            prd_seq_id : data[i].prd_seq_id,
                            prd_grade : outObj.prd_grade,
                            prd_qty : outObj.prd_qty,
                            slot_no : outObj.slot_no
                        }
                        Data.push(dataObj);
                    }
                }
                domObj.$boxIdFk.val("");
                clearDataAction();
                setGridInfo(Data, "#glassListGrd");
            };
            if(rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
            function fixdata(data) { //文件流转BinaryString
                var o = "", l = 0, w = 10240;
                for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                return o;
            }
        }
        domObj.$boxIdFk.keydown(function(event) {

            if (event.which == 13) {
                btnFunc.queryBtnfunc();
                btnFunc.iniCstHold();
            }
        });
        function initFunc() {
            var crr_query="Y";
            domObj.$boxIdFk.val("");
            iniGridInfo();
            iniButtonAction();
            inModelGrid();// 初始化dailog中的grids
            otherActionBind();
            clearDataAction();
        }
        initFunc();
        var crr_query="Y";
        //表格自适应
        function resizeFnc(){
            var offsetBottom, divWidth, divWidth1,offsetBottom1,divWidth2,offsetBottom2;
            divWidth = $("#glassListDiv").width();
            offsetBottom = $(window).height() - $("#glassListDiv").offset().top;
            // offsetBottom = $("#glassListDiv").offset().top;
            $("#glassListDiv").height(offsetBottom * 0.95);
            $("#glassListGrd").setGridWidth(divWidth * 0.99);
            $("#glassListGrd").setGridHeight(offsetBottom * 0.99 - 150);

            divWidth1 = $("#divTotal").width();
            offsetBottom1 = $(window).height() - $("#divTotal").offset().top;
            $("#divTotal").height(offsetBottom1 * 0.44);
            $("#ReasonListGrd").setGridWidth(divWidth1 * 0.85);
            $("#ReasonListGrd").setGridHeight(offsetBottom1 * 0.40 - 190);

            divWidth2 = $("#divTotal").width();
            offsetBottom2 = $(window).height() - $("#divTotal").offset().top;
            $("#divTotal").height(offsetBottom2 * 0.40);
            $("#cstHoldListGrd").setGridWidth(divWidth2 * 0.85);
            $("#cstHoldListGrd").setGridHeight(offsetBottom2 * 0.52 - 65);
        };
        resizeFnc();
        $(window).resize(function() {
            resizeFnc();
        });
    })